<template>
  <el-main>
    <el-row>
      <!-- <el-col v-if="state.authHide" :span="24" style="margin-bottom:12px;" >
        <el-button type="warning" style="width:100%;" @click="onAuth">授权通知</el-button>
      </el-col> -->
      <el-col :span="24" style="margin-bottom:12px;" >
        <el-date-picker
          v-model="state.time"
          type="datetime"
          placeholder="请选择时间"
          :shortcuts="shortcuts"
          style="width:100%;"
          :disabled="state.startFlag"
        />  
      </el-col>

      <el-col v-if="state.startFlag" :span="24" style="margin-bottom:12px;" >
        <el-input v-model="state.text" disabled placeholder="倒计时" />
      </el-col>

      <el-col :span="24" style="margin-bottom:12px;" >
        <el-input v-model="state.title" placeholder="通知标题" />
      </el-col>

      <el-col :span="24" style="margin-bottom:12px;" >
        <el-input v-model="state.message" placeholder="通知内容" />
      </el-col>

      <el-col :span="24" style="margin-bottom:12px;" >
        <el-input v-model="state.url" placeholder="跳转链接" />
      </el-col>

      <el-col :span="24" style="margin-bottom:12px;" >
        <el-button v-if="!state.startFlag" type="primary" style="width:100%;" @click="handleStart">开始</el-button>
        <el-button v-else type="danger" style="width:100%;" @click="handleStop">清除</el-button>
      </el-col>
    </el-row>
  </el-main>
</template>
<script lang="ts" setup>
import { onMounted, reactive} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { OpenUrl } from '../utils/index'
const state = reactive({
  authHide: false,
  time: new Date(),
  muTime: 0,
  title: '通知标题',
  message: '通知内容',
  text: '',
  url: 'https://www.baidu.com',
  startFlag: false,
})

const shortcuts = [
  {
    text: '10秒',
    value: () => new Date(new Date().getTime() + 10  * 1000),
  },
  {
    text: '5分',
    value: () => new Date(new Date().getTime() + 5 * 60 * 1000),
  },
  {
    text: '10分',
    value: () => new Date(new Date().getTime() + 10 * 60 * 1000),
  },
  {
    text: '15分',
    value: () => new Date(new Date().getTime() + 15 * 60 * 1000),
  },
  {
    text: '30分',
    value: () => new Date(new Date().getTime() + 15 * 60 * 1000),
  },
  {
    text: '1时',
    value: () => new Date(new Date().getTime() + 60 * 60 * 1000),
  },
  {
    text: '2时',
    value: () => new Date(new Date().getTime() + 60 * 2 * 60 * 1000),
  },
]

onMounted(( ) => {
  state.authHide = (window.Notification && Notification.permission != "granted") ? true : false;
});

// 格式化时间
function formatTime(seconds:number) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;

    // 格式化时间，确保每个部分都是两位数
    const formattedHours = String(hours).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(remainingSeconds).padStart(2, '0');

    return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

let interval: any
function startInterval() {
  state.startFlag = true
  if (interval) clearInterval(interval);
  const lastTime = state.time.getTime()

  const intervalFun = () => {
    const now = new Date()
    if (now.getTime() >= lastTime) {
      clearInterval(interval)
      ElMessage.success('已到时间:' + state.time.toLocaleString())
      state.startFlag = false
      triggerNotification()
      ElMessageBox.alert('计时已到', '通知', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: '确认',
        callback: () => {
          state.startFlag = false
        },
      })
      return ;
      // greet()
    }
    state.muTime = Math.floor((lastTime - now.getTime()) / 1000)
    state.text = `倒计时：${formatTime(state.muTime)}`
  }

  intervalFun();
  interval = setInterval(intervalFun, 1000);
}

function triggerNotification() {
  const n = new Notification(state.title, {
        body: state.message,
        requireInteraction: true,
        icon: "https://tse2-mm.cn.bing.net/th/id/OIP-C.7pmotRzx9Y73PO4ax0dmhAHaHa?w=186&h=186&c=7&r=0&o=5&pid=1.7", // 可选的图标URL
        data: { url: state.url ?? '' } // 传递跳转的URL
    });
    n.onclick = () => {
        n.close(); // 关闭通知
        if (n.data.url) {
            OpenUrl(n.data.url);
            ElMessage.success('点击了通知，跳转网址中..' + n.data.url);
        } else ElMessage.success('点击了通知');
    }
    ElMessage.success('通知发送成功');
}

// 开始
function handleStart() {
  if(state.time.getTime() < new Date().getTime())return  ElMessage.error('通知时间不能小于当前时间');
  ElMessage.success('通知时间:' + state.time.toLocaleString())
  startInterval();
}

// 停止
function handleStop() {
  state.startFlag = false
  clearInterval(interval)
}

// 授权通知
const onAuth = () => { 
    if (window.Notification && Notification.permission !== "granted") {
        Notification.requestPermission(function(status) {
          if (Notification.permission !== status) {
            // @ts-ignore
            Notification.permission = status;
          }
        });
    }
}
</script>
<style scoped>
</style>
